import 'package:mobx/mobx.dart';
import '../models/marine_protection_model.dart';
import '../models/user_submission_model.dart';
import '../models/emoji_model.dart';
import 'auth_store.dart';
import 'package:hive/hive.dart';
import 'package:uuid/uuid.dart';

part 'marine_protection_store.g.dart';

class MarineProtectionStore = _MarineProtectionStore
    with _$MarineProtectionStore;

abstract class _MarineProtectionStore with Store {
  final Box<MarineProtectionModel> _activityBox =
      Hive.box<MarineProtectionModel>('marine_protections');
  final Box<UserSubmissionModel> _submissionBox = Hive.box<UserSubmissionModel>(
    'user_submissions',
  );
  final Box<EmojiModel> _emojiBox = Hive.box<EmojiModel>('emojis');
  final AuthStore _authStore;
  final Uuid _uuid = Uuid();

  _MarineProtectionStore(this._authStore);

  @observable
  ObservableList<MarineProtectionModel> activities =
      ObservableList<MarineProtectionModel>();

  @observable
  ObservableList<UserSubmissionModel> userSubmissions =
      ObservableList<UserSubmissionModel>();

  @observable
  ObservableList<EmojiModel> emojis = ObservableList<EmojiModel>();

  @observable
  bool isLoading = false;

  @observable
  String? errorMessage;

  @computed
  List<EmojiModel> get unlockedEmojis {
    if (_authStore.currentUser == null) return [];
    return emojis.where((emoji) => emoji.isUnlocked).toList();
  }

  @action
  Future<void> loadActivities() async {
    isLoading = true;
    errorMessage = null;

    try {
      final loadedActivities = _activityBox.values.toList();
      activities.clear();
      activities.addAll(loadedActivities);
      isLoading = false;
    } catch (e) {
      errorMessage = 'Load activities failed: ${e.toString()}';
      isLoading = false;
    }
  }

  @action
  Future<void> loadUserSubmissions() async {
    if (_authStore.currentUser == null) return;

    isLoading = true;
    errorMessage = null;

    try {
      final userId = _authStore.currentUser!.id;
      final loadedSubmissions =
          _submissionBox.values
              .where((submission) => submission.userId == userId)
              .toList();

      userSubmissions.clear();
      userSubmissions.addAll(loadedSubmissions);
      isLoading = false;
    } catch (e) {
      errorMessage = 'Load user submissions failed: ${e.toString()}';
      isLoading = false;
    }
  }

  @action
  Future<void> loadEmojis() async {
    isLoading = true;
    errorMessage = null;

    try {
      final loadedEmojis = _emojiBox.values.toList();
      emojis.clear();
      emojis.addAll(loadedEmojis);
      isLoading = false;
    } catch (e) {
      errorMessage = 'Load emojis failed: ${e.toString()}';
      isLoading = false;
    }
  }

  @action
  Future<bool> submitToActivity(String activityId, String imageUrl) async {
    if (_authStore.currentUser == null) return false;

    isLoading = true;
    errorMessage = null;

    try {
      // 创建提交记录
      final submission = UserSubmissionModel(
        id: _uuid.v4(),
        userId: _authStore.currentUser!.id,
        imageUrl: imageUrl,
        activityId: activityId,
        submitDate: DateTime.now(),
      );

      // 保存提交记录
      await _submissionBox.put(submission.id, submission);
      userSubmissions.add(submission);

      // 解锁对应的表情
      final activity = _activityBox.values.firstWhere(
        (activity) => activity.id == activityId,
      );

      final emoji = _emojiBox.values.firstWhere(
        (emoji) => emoji.id == activity.rewardEmojiId,
      );

      emoji.unlock();
      await _emojiBox.put(emoji.id, emoji);

      // 刷新列表
      await loadEmojis();

      isLoading = false;
      return true;
    } catch (e) {
      errorMessage = 'Submit image failed: ${e.toString()}';
      isLoading = false;
      return false;
    }
  }

  @action
  Future<void> initializeDefaultActivities() async {
    // 仅在数据库为空时初始化默认活动和表情
    if (_activityBox.isEmpty && _emojiBox.isEmpty) {
      // 创建默认表情
      final emoji1 = EmojiModel(
        id: _uuid.v4(),
        path: 'assets/images/good.png',
        activityId: 'activity1',
        name: 'good',
      );

      final emoji2 = EmojiModel(
        id: _uuid.v4(),
        path: 'assets/images/clap.png',
        activityId: 'activity2',
        name: 'clap',
      );

      final emoji3 = EmojiModel(
        id: _uuid.v4(),
        path: 'assets/images/love.png',
        activityId: 'activity3',
        name: 'love',
      );

      final emoji4 = EmojiModel(
        id: _uuid.v4(),
        path: 'assets/images/cheer.png',
        activityId: 'activity4',
        name: 'cheer',
      );

      // 保存表情
      await _emojiBox.put(emoji1.id, emoji1);
      await _emojiBox.put(emoji2.id, emoji2);
      await _emojiBox.put(emoji3.id, emoji3);
      await _emojiBox.put(emoji4.id, emoji4);

      // 创建官方活动
      final activity1 = MarineProtectionModel(
        id: 'activity1',
        title: 'Clean up marine debris.',
        description:
            'Reduce marine debris pollution, protect clean water environment, and restore vitality and purity to every piece of blue. ',
        imageUrl: 'assets/images/protection1.png',
        startDate: DateTime.now(),
        endDate: DateTime.now().add(Duration(days: 30)),
        location: 'Great Barrier Reef',
        rewardEmojiId: emoji1.id,
      );

      final activity2 = MarineProtectionModel(
        id: 'activity2',
        title: 'Save marine life',
        description:
            'Protect endangered or threatened marine life and their habitats, and promote marine biodiversity.',
        imageUrl: 'assets/images/protection2.png',
        startDate: DateTime.now(),
        endDate: DateTime.now().add(Duration(days: 30)),
        location: 'Global ocean',
        rewardEmojiId: emoji2.id,
      );

      final activity3 = MarineProtectionModel(
        id: 'activity3',
        title: 'Beach Cleaning Action',
        description:
            'Organize volunteers to clean up plastic and garbage on the beach to reduce the source of pollution.',
        imageUrl: 'assets/images/protection3.png',
        startDate: DateTime.now(),
        endDate: DateTime.now().add(Duration(days: 30)),
        location: 'Caribbean Sea',
        rewardEmojiId: emoji3.id,
      );

      final activity4 = MarineProtectionModel(
        id: 'activity4',
        title: 'Environmental protection publicity',
        description:
            'Through exhibitions, lectures and online publicity, we popularize marine environmental protection knowledge to the public.',
        imageUrl: 'assets/images/protection4.png',
        startDate: DateTime.now(),
        endDate: DateTime.now().add(Duration(days: 30)),
        location: 'Ocean Park',
        rewardEmojiId: emoji4.id,
      );

      // 保存活动
      await _activityBox.put(activity1.id, activity1);
      await _activityBox.put(activity2.id, activity2);
      await _activityBox.put(activity3.id, activity3);
      await _activityBox.put(activity4.id, activity4);

      // 刷新列表
      await loadActivities();
      await loadEmojis();
    }
  }
}
